package org.example.util;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.example.model.User;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;


public class WebUtil {
    public static final ObjectMapper MAPPER = new ObjectMapper();

    //初始化
    static {
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        MAPPER.setDateFormat(df);
    }

    public static void serialize(HttpServletResponse resp, Object o) {
        resp.setContentType("application/json");
        resp.setCharacterEncoding("utf-8");
        try {
            String json = MAPPER.writeValueAsString(o);
            resp.getWriter().write(json);
        } catch (IOException e) {
            e.printStackTrace();
            resp.setStatus(500);
        }
    }

    // 反序列化：把请求正文中的json字符串，转换为Java对象
    public static <T> T deserialize(HttpServletRequest req, Class<T> clazz) {
        try {
            return MAPPER.readValue(req.getInputStream(), clazz);
        } catch (IOException e) {
            throw new RuntimeException("json反序列化错误", e);
        }
    }

    public static User validateLogin(HttpServletRequest req) {
        HttpSession session = req.getSession(false);
        User user = null;
        if(session != null){
            //这里是提前写了获取会话中的用户信息，登录时注意要保存相同的键
            user = (User) session.getAttribute("user");
        }
        return user;
    }
}
